﻿using System;
using EOSCRM.Domain;
using EOSCRM.Dao;
using EOSCRM.Web.Common;

namespace EOSCRM.Web
{
    public partial class Login : System.Web.UI.Page
    {
        private readonly UserAdminDao _objServ = new UserAdminDao();
        private readonly UserLogDao _urLog = new UserLogDao();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                txtUserName.Focus();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (CheckLogin())
            {
                new ConfigDao();
                Response.Redirect(WebUrlConstants.HOME_PAGE, false);
            }
        }

        private bool CheckLogin()
        {
            try
            {
                if (Page.IsValid)
                {
                    //var encryptString = EncryptUtil.Encrypt("Data Source=.;Initial Catalog=EOSDN;Persist Security Info=True;User ID=sa;Password=123456");

                    var objUi = new UserAdmin
                                    {
                                        Username = txtUserName.Text.Trim()
                                    };
                    var password = txtPassword.Text.Trim(); //CommonFunc.MD5(txtPassword.Text.Trim());
                    objUi.Password = password;
                    var objDb = _objServ.CheckLogin(objUi);

                    if(objDb != null)
                    {
                        Session[SessionKey.USER_LOGIN] = objDb;
                        Session[_urLog.SessionIdentify] = _urLog.New(objDb.MaNV);
                        Session["ComputerName"] = UserEventLog.ClientHost();
                        Session["IpAdress"] = UserEventLog.ClientIP();
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                return false;
            }

            return false;
        }
        protected void btnReset_Click(object sender, EventArgs e)
        {
            txtUserName.Text = string.Empty;
            txtPassword.Text = string.Empty;
            txtUserName.Focus();
        }
    }
}